package com.cz.basetool.ui_work.util.image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;

import com.cz.basetool.ui_work.util.log.AndroidConsoleLogPrinter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片压缩工具类
 * author:Created by ChenZhang on 2016/7/7 0007.
 * function:
 */
public class ImageCompressUtil {
    private static final String TAG = "ImageCompressUtil";
    /**
     * caculate the bitmap sampleSize
     * @param options
     * @param rqsW
     * @param rqsH
     * @return
     */
    public final static int caculateInSampleSize(BitmapFactory.Options options, int rqsW, int rqsH) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (rqsW == 0 || rqsH == 0) return 1;
        if (height > rqsH || width > rqsW) {
            final int heightRatio = Math.round((float) height/ (float) rqsH);
            final int widthRatio = Math.round((float) width / (float) rqsW);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }


    public static BitmapFactory.Options getBitmapSize(String sFile) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(sFile, options);
        return options;
    }

//    /**
//     * 将Bitmap压缩
//     * @param path  原图片路径
//     * @return
//     */
//    public static Bitmap compress(String path,Bitmap bitmapToScale){
//        //从文件里得到Bitmap对象
//        if(bitmapToScale != null){
//            int width = bitmapToScale.getWidth();
//            int height = bitmapToScale.getHeight();
//            float scale = 0.8f;
//            CZLocalLogPrinter.getInstance().writeLog("压缩图片");
//            CZLocalLogPrinter.getInstance().writeLog("压缩前尺寸","height = " + (int)(height)  + " width = " + (int)(width));
//            CZLocalLogPrinter.getInstance().writeLog("压缩后期望尺寸","height = " + (int)(height * scale)  + " width = " + (int)(width * scale));
//
//            TLog.d("压缩后图片尺寸：" + "height = " + (int)(height * scale)  + " width = " + (int)(width * scale));
//            Bitmap bitmap = getScaledBitmap(path, (int)(width *scale),(int)(height * scale));
//            CZLocalLogPrinter.getInstance().writeLog("压缩后实际尺寸","height = " + bitmap.getHeight()  + " width = " + bitmap.getWidth());
//
//            return bitmap;
//        }
//        return null;
//    }


    /**
     * 将Bitmap压缩成600*800像素大小比例
     * @param path  原图片路径
     * @return
     */
    public static Bitmap compressFirst(String path,Bitmap bitmapToScale){
        File bitmapFile = new File(path);
        //从文件里得到Bitmap对象
        if(bitmapToScale != null){
            int width = bitmapToScale.getWidth();
            int height = bitmapToScale.getHeight();
            float rqw = 600f;
            float rqh = 800f;
            float scale =  Math.min(rqw / width,rqh / height);
            AndroidConsoleLogPrinter.d(TAG,"压缩图片至600*800");
            AndroidConsoleLogPrinter.d(TAG,"图片路径" + path);
            AndroidConsoleLogPrinter.d(TAG,"压缩前尺寸" + "height = " + (int)(height)  + " width = " + (int)(width));
            AndroidConsoleLogPrinter.d(TAG,"压缩后期望尺寸" + "height = " + (int)(height * scale)  + " width = " + (int)(width * scale));
            Bitmap bitmap = getScaledBitmap(path, (int)(width *scale),(int)(height * scale));
            String newBitmpSize = PhotoFileUtils.formatFileSize(bitmapFile.length(), PhotoFileUtils.SIZETYPE_MB) + "M";
            AndroidConsoleLogPrinter.d(TAG,"压缩后实际尺寸" + "height = " + bitmap.getHeight()  + " width = " + bitmap.getWidth() + " size = " + newBitmpSize);
            return bitmap;
        }
        return null;
    }

    /**
     * 保证图片小于50KB
     * @param path
     * @param bitmapSource
     * @return
     */
    public final static Bitmap compressBitmapQuality(String path, Bitmap bitmapSource) {
        File bitmapFile = new File(path);
        ByteArrayOutputStream baos = null;
        FileOutputStream outStream = null;
        try {
            AndroidConsoleLogPrinter.d(TAG,"压缩图片至50KB");
            AndroidConsoleLogPrinter.d(TAG,"图片路径" + path);
            String bitmapSourceSize = PhotoFileUtils.formatFileSize(bitmapSource.getByteCount(), PhotoFileUtils.SIZETYPE_MB) + "M";
            AndroidConsoleLogPrinter.d(TAG,"压缩前尺寸" + "height = " + bitmapSource.getHeight()  + " width = " + bitmapSource.getWidth() + "  size = " + bitmapSourceSize);

            baos = new ByteArrayOutputStream();
            int options = 100;
            bitmapSource.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            while (baos.toByteArray().length>=50*1024) {
                baos.reset();
                options -= 5;
                bitmapSource.compress(Bitmap.CompressFormat.JPEG, options, baos);
            }
            File file = new File(path);
            outStream = new FileOutputStream(file);
            outStream.write(baos.toByteArray());
            outStream.flush();// 刷新此缓冲区的输出流
            Bitmap newBitmap = ImageCommonUtil.getBitmapFromPath(path);
            String newBitmpSize = PhotoFileUtils.formatFileSize(bitmapFile.length(), PhotoFileUtils.SIZETYPE_MB) + "M";
            AndroidConsoleLogPrinter.d(TAG,"压缩后实际尺寸" + "height = " + newBitmap.getHeight()  + " width = " + newBitmap.getWidth() + " size = " + newBitmpSize);
            return newBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(outStream != null){
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    private static void writeBitmapToSourcePath(Bitmap bitmap,String sourcePath){
        ByteArrayOutputStream baos = null;
        FileOutputStream outStream = null;
        try {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            File file = new File(sourcePath);
            outStream = new FileOutputStream(file);
            outStream.write(baos.toByteArray());
            outStream.flush();// 刷新此缓冲区的输出流
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(outStream != null){
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 压缩指定路径的图片，并得到图片对象
     * @param path
     * @param rqsW
     * @param rqsH
     * @return
     */
    public final static Bitmap compressBitmap(String path, int rqsW, int rqsH) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = caculateInSampleSize(options, rqsW, rqsH);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }




    // 按比例缩放
    public static float getBitmapScale(BitmapFactory.Options options, int dWidth, int dHeight) {
        float scale = 0;
        if (options.outHeight > dHeight || options.outWidth > dWidth) {
            if ((options.outWidth * dHeight) > (options.outHeight * dWidth)) {
                scale = (float) dWidth / (float) options.outWidth;
                // scaleHeight = (float) options.outHeight / (float) options.outWidth;
            } else {
                scale = (float) dHeight / (float) options.outHeight;
                // scaleWidth = (float) options.outWidth / (float) options.outHeight;
            }
        } else {
            scale = 1;
        }
        return scale;
    }


    /**
     * 无损压缩图片
     *
     * @param sFile
     *            原图片位置
     * @param dFile
     *            压缩后保存位置
     * @param dWidth
     *            宽度
     * @param dHeight
     *            高度
     * @param flag
     *            压缩质量 1-100
     * @throws IOException
     */
    public static void getPicThumbnail(String sFile, String dFile, int dWidth, int dHeight, int flag) throws IOException {
        BitmapFactory.Options options = getBitmapSize(sFile);
        Bitmap bitmap = BitmapFactory.decodeFile(sFile);
        FileOutputStream fos = new FileOutputStream(dFile);
        float scale = getBitmapScale(options, dWidth, dHeight);
        if (scale != 1.0f) {
            Matrix m = new Matrix();
            m.postScale(scale, scale);
            Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, options.outWidth, options.outHeight, m, true);
            newBitmap.compress(Bitmap.CompressFormat.JPEG, flag, fos);
            if (!newBitmap.isRecycled()) {
                newBitmap.recycle();
                newBitmap = null;
            }
        } else {
            bitmap.compress(Bitmap.CompressFormat.JPEG, flag, fos);
        }
        fos.flush();
        fos.close();
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

    }

    public static Bitmap getScaledBitmap(String sFile, int dWidth, int dHeight){
        BitmapFactory.Options options = getBitmapSize(sFile);
        Bitmap bitmap = BitmapFactory.decodeFile(sFile);
        float scale = getBitmapScale(options, dWidth, dHeight);
        if (scale < 1.0f) {
            Matrix m = new Matrix();
            m.postScale(scale, scale);
            Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, options.outWidth, options.outHeight, m, true);
            writeBitmapToSourcePath(bitmap,sFile);
            return newBitmap;
        } else {
            return bitmap;
        }
    }

    public static void getPicThumbnail(String sFile, String dFile) throws IOException {
        getPicThumbnail(sFile, dFile, 1280, 1280, 100);
    }
}
